import type { SimpleUserInfo } from '../auth/auth';
import { fromError, initAxios } from '../common';
import type { ApiResponse } from '../common';

const client = initAxios();

export type CommentInfo = {
  id: number;
  author: SimpleUserInfo;
  chapter: {
    id: number;
    title: string;
  };
  novel: {
    id: number;
    title: string;
  },
  content: string;
  created_at: string;
};

export type CommentListResponse = {
  total: number;
  comments: CommentInfo[];
};

export type PostCommentForm = {
  chapter_id: number;
  content: string;
};

export async function createComment(cid: number, content: string) {
  try {
    const payload = { cid, content };
    const resp = await client.post<ApiResponse<{ id: string }>>('/api/comment/create', payload);
    return resp.data;
  } catch (error) {
    return fromError(error);
  }
}

export type UpdateCommentForm = {
  id: number;
  content: string;
};

// 添加保存评论的操作函数
export async function saveComment(data: UpdateCommentForm) {
  try {
    const resp = await client.put<ApiResponse<{ id: string }>>(`/api/comment/${data.id}`, { content: data.content });
    return resp.data;
  } catch (error) {
    return fromError(error);
  }
}

export async function getCommentsByChapterId(chapterId: number, page = 1, pageSize = 10) {
  try {
    const resp = await client.get<ApiResponse<CommentListResponse>>(`/api/comment/${chapterId}`, {
      params: { page, pageSize },
    });
    return resp.data;
  } catch (error) {
    return fromError(error);
  }
}

export async function deleteComment(id: number) {
  try {
    const resp = await client.delete<ApiResponse<boolean>>(`/api/comment/${id}`);
    return resp.data;
  } catch (error) {
    return fromError(error);
  }
}

// 添加搜索评论的操作函数
export async function queryComment(keyword: string, page = 1, pageSize = 10) {
  try {
    const resp = await client.get<ApiResponse<CommentListResponse>>('/api/comment/search', {
      params: { keyword, page, pageSize },
    });
    return resp.data;
  } catch (error) {
    return fromError(error);
  }
}

